package com.chenj.springbootgrpcclient;

import com.chenj.grpc.lib.HelloReply;
import com.chenj.grpc.lib.HelloRequest;
import com.chenj.grpc.lib.SimpleGrpc;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.StatusRuntimeException;

/**
 * <p>
 * 类注释
 * </p>
 *
 * @author liyi
 * @since 2024/6/11 10:24
 */
public class HelloWorldClientTest {
    private final SimpleGrpc.SimpleBlockingStub blockingStub;

    public HelloWorldClientTest(ManagedChannel channel) {
        blockingStub = SimpleGrpc.newBlockingStub(channel);
    }

    public void greet(String name) {
        HelloRequest request = HelloRequest.newBuilder().setName(name).build();
        HelloReply response;
        try {
            response = blockingStub.sayHello(request);
            System.out.println("Greeting: " + response.getMessage());
        } catch (StatusRuntimeException e) {
            System.err.println("RPC failed: " + e.getStatus());
        }
    }

    public static void main(String[] args) throws Exception {
        ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 9090)
                .usePlaintext()
                .build();

        HelloWorldClientTest client = new HelloWorldClientTest(channel);
        client.greet("world");

        channel.shutdownNow().awaitTermination(5, java.util.concurrent.TimeUnit.SECONDS);
    }
}
